package com.ruoyi.common.utils.huoshan;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Copyright (year) Beijing Volcano Engine Technology Ltd.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class CVProcess {

    private static final BitSet URLENCODER = new BitSet(256);

    private static final String CONST_ENCODE = "0123456789ABCDEF";
    public static final Charset UTF_8 = StandardCharsets.UTF_8;

    private final String region;
    private final String service;
    private final String schema;
    private final String host;
    private final String path;
    private final String ak;
    private final String sk;

    static {
        int i;
        for (i = 97; i <= 122; ++i) {
            URLENCODER.set(i);
        }

        for (i = 65; i <= 90; ++i) {
            URLENCODER.set(i);
        }

        for (i = 48; i <= 57; ++i) {
            URLENCODER.set(i);
        }
        URLENCODER.set('-');
        URLENCODER.set('_');
        URLENCODER.set('.');
        URLENCODER.set('~');
    }

    public CVProcess(String region, String service, String schema, String host, String path, String ak, String sk) {
        this.region = region;
        this.service = service;
        this.host = host;
        this.schema = schema;
        this.path = path;
        this.ak = ak;
        this.sk = sk;
    }
    public static String convertImageToBase64(String imagePath) throws IOException {
        // 读取图片文件
        File file = new File(imagePath);
        FileInputStream fileInputStream = new FileInputStream(file);

        // 创建字节数组
        byte[] bytes = new byte[(int) file.length()];
        fileInputStream.read(bytes);
        fileInputStream.close();

        // 使用Base64编码
        return Base64.getEncoder().encodeToString(bytes);
    }
    public static void generations(String imgPath) throws Exception {
        String AccessKeyID = "AKLTNmQzNDRiY2M5ZTJiNDIwODg4MDJiMmIwMWVlY2JlMTM";
        String SecretAccessKey = "TjJRd05UVmhNemhpWW1JeE5EVTVNbUl5T0dFeVlUSmpPV1U1WlRabE9HRQ==";
        // 请求地址
        String endpoint = "visual.volcengineapi.com";
        String path = "/"; // 路径，不包含 Query// 请求接口信息
        String service = "cv";
        String region = "cn-north-1";
        String schema = "https";
        CVProcess sign = new CVProcess(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);

        String action = "Img2ImgXLSft";
        String version = "2022-08-31";

        Date date = new Date();
        HashMap<String, String> queryMap = new HashMap<>() {{
            put("Limit", "1");
        }};
        String imgBasee64 = convertImageToBase64(imgPath);
        ArrayList<String> binaryData = new ArrayList<>();
        binaryData.add(imgBasee64);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("req_key", "i2i_xl_sft");
        jsonObject.put("model_version", "2022-08-31");
//        jsonObject.put("req_schedule_conf", "general_v20_9B_pe");
        jsonObject.put("prompt", "3D images created using computer graphics. They have both realistic and unrealistic elements. Characters are exaggerated and characterized, while objects' textures are delicately expressed to make the image lively and unique. Bright and vibrant colors are generally used.背景为白色");
        jsonObject.put("scale", 22);
        jsonObject.put("binary_data_base64", binaryData);
        jsonObject.put("return_url", true);
        jsonObject.put("width", 1024);
        jsonObject.put("height", 1024);
        Random random = new Random();
        int randomNumber = 10000000 + random.nextInt(90000000); // 确保是 8 位
        jsonObject.put("seed", randomNumber);
        JSONObject controlnetArgsJo = new JSONObject();
        controlnetArgsJo.put("type","canny");
        controlnetArgsJo.put("strength",0.5);
        controlnetArgsJo.put("binary_data_index",0);
        ArrayList<JSONObject> controlnetArgsList = new ArrayList<>();
        controlnetArgsList.add(controlnetArgsJo);
        jsonObject.put("controlnet_args",controlnetArgsList);

        String response = sign.doRequest("POST", queryMap, JSONObject.toJSONBytes(jsonObject), date, action, version);
        // 处理返回结果中的 \u0026 转换为 &
        response = processResponse(response);
        System.out.println(response);
    }

    public static void main(String[] args) throws Exception {
        generations("D:\\BaiduNetdiskDownload\\线稿\\Object_3k\\1_Natural\\5_Humans\\1人\\swtp_01126_la.jpg");
    }

    public String doRequest(String method, Map<String, String> queryList, byte[] body,
                            Date date, String action, String version) throws Exception {
        if (body == null) {
            body = new byte[0];
        }
        String xContentSha256 = hashSHA256(body);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String xDate = sdf.format(date);
        String shortXDate = xDate.substring(0, 8);
        String contentType = "application/json";
        String signHeader = "host;x-date;x-content-sha256;content-type";


        SortedMap<String, String> realQueryList = new TreeMap<>(queryList);
        realQueryList.put("Action", action);
        realQueryList.put("Version", version);
        StringBuilder querySB = new StringBuilder();
        for (String key : realQueryList.keySet()) {
            querySB.append(signStringEncoder(key)).append("=").append(signStringEncoder(realQueryList.get(key))).append("&");
        }
        querySB.deleteCharAt(querySB.length() - 1);

        String canonicalStringBuilder = method + "\n" + path + "\n" + querySB + "\n" +
                "host:" + host + "\n" +
                "x-date:" + xDate + "\n" +
                "x-content-sha256:" + xContentSha256 + "\n" +
                "content-type:" + contentType + "\n" +
                "\n" +
                signHeader + "\n" +
                xContentSha256;

        System.out.println(canonicalStringBuilder);

        String hashcanonicalString = hashSHA256(canonicalStringBuilder.getBytes());
        String credentialScope = shortXDate + "/" + region + "/" + service + "/request";
        String signString = "HMAC-SHA256" + "\n" + xDate + "\n" + credentialScope + "\n" + hashcanonicalString;

        byte[] signKey = genSigningSecretKeyV4(sk, shortXDate, region, service);
        String signature = HexFormat.of().formatHex(hmacSHA256(signKey, signString));


        URL url = new URL(schema + "://" + host + path + "?" + querySB);


        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setRequestProperty("Host", host);
        conn.setRequestProperty("X-Date", xDate);
        conn.setRequestProperty("X-Content-Sha256", xContentSha256);
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("Authorization", "HMAC-SHA256" +
                " Credential=" + ak + "/" + credentialScope +
                ", SignedHeaders=" + signHeader +
                ", Signature=" + signature);
        if (!Objects.equals(conn.getRequestMethod(), "GET")) {
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(body);
            os.flush();
            os.close();
        }
        conn.connect();

        int responseCode = conn.getResponseCode();

        InputStream is;
        if (responseCode == 200) {
            is = conn.getInputStream();
        } else {
            is = conn.getErrorStream();
        }
        String responseBody = new String(is.readAllBytes());
        is.close();

        return responseBody;
    }

    private String signStringEncoder(String source) {
        if (source == null) {
            return null;
        }
        StringBuilder buf = new StringBuilder(source.length());
        ByteBuffer bb = UTF_8.encode(source);
        while (bb.hasRemaining()) {
            int b = bb.get() & 255;
            if (URLENCODER.get(b)) {
                buf.append((char) b);
            } else if (b == 32) {
                buf.append("%20");
            } else {
                buf.append("%");
                char hex1 = CONST_ENCODE.charAt(b >> 4);
                char hex2 = CONST_ENCODE.charAt(b & 15);
                buf.append(hex1);
                buf.append(hex2);
            }
        }

        return buf.toString();
    }

    public static String hashSHA256(byte[] content) throws Exception {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");

            return HexFormat.of().formatHex(md.digest(content));
        } catch (Exception e) {
            throw new Exception(
                    "Unable to compute hash while signing request: "
                            + e.getMessage(), e);
        }
    }

    public static byte[] hmacSHA256(byte[] key, String content) throws Exception {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(key, "HmacSHA256"));
            return mac.doFinal(content.getBytes());
        } catch (Exception e) {
            throw new Exception(
                    "Unable to calculate a request signature: "
                            + e.getMessage(), e);
        }
    }

    private byte[] genSigningSecretKeyV4(String secretKey, String date, String region, String service) throws Exception {
        byte[] kDate = hmacSHA256((secretKey).getBytes(), date);
        byte[] kRegion = hmacSHA256(kDate, region);
        byte[] kService = hmacSHA256(kRegion, service);
        return hmacSHA256(kService, "request");
    }

    // 处理返回结果中 image_urls 中的 \u0026 转换为 & 的方法
    private static String processResponse(String response) {
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.containsKey("image_urls")) {
            JSONArray imageUrlsArray = jsonObject.getJSONArray("image_urls");
            for (int i = 0; i < imageUrlsArray.size(); i++) {
                String imageUrl = imageUrlsArray.getString(i);
                imageUrl = imageUrl.replaceAll("\\u0026", "&");
                imageUrlsArray.set(i, imageUrl);
            }
            jsonObject.put("image_urls", imageUrlsArray);
        }
        return jsonObject.toJSONString();
    }
}